<template>
    <div class="video">
        <div class="title">{{ $t('my.我的视频') }}</div>

        <div class="tabs">
            <div class="item" @click="dialogVisible = true">
                {{ $t('live.发布视频') }}
            </div>
        </div>

        <div class="list">
            <div class="item" v-for="(item, index) in list" :key="item.id" @click="router(item)">
                <img :src="item.image" class="cover" v-show="playingId !== item.id">
                <video ref="videoEls" :id="'video_' + item.id" :src="item.video" :poster="item.image" class="video_item" @play="onPlay(item.id)"
                    @pause="onPause(item.id)" @ended="onEnded(item.id)" @click.stop="togglePlay(item)" controls></video>
                <img src="@/assets/image/play2.png" alt="" class="play" v-show="playingId !== item.id">
                <img src="@/assets/image/dele.png" alt="" class="dele" @click.stop="removeVideo(item, index)"
                    v-show="playingId !== item.id">

            </div>
        </div>
        <div class="page_view">
            <el-pagination background layout="prev, pager, next" :current-page="page" :total="total"
                @current-change="change" />
        </div>

        <el-dialog :title="$t('live.发布视频')" :visible.sync="dialogVisible" top="50px" width="530px" :modal="true"
            :center="true" :show-close="false" append-to-body destroy-on-close>
            <AddVideo @ok="dialog_ok" @close="dialogVisible = false"/>
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from 'vuex';

import AddVideo from "@/components/my/AddVideo.vue"

export default {
    components: {
        AddVideo
    },
    data() {
        return {
            page: 1,
            limit: 10,
            list: [],
            total: 0,

            playingId: null, // 使用视频ID记录当前播放的视频，避免新增视频后索引错乱
            dialogVisible: false
        }
    },
    computed: {
        ...mapState({
            user: state => state.user
        })
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            // 保存当前播放的视频ID，用于后续检查
            const previousPlayingId = this.playingId;
            
            // 在获取新列表前，暂停当前正在播放的视频
            if (previousPlayingId) {
                const currentVideo = this.getVideoElementById(previousPlayingId);
                if (currentVideo && !currentVideo.paused) {
                    currentVideo.pause();
                }
                this.playingId = null;
            }
            
            let {
                list: res
            } = await this.$api.videoApi.videoList({
                user_id: this.user.user_id,
                page: this.page,
                page_size: this.limit
            });
            this.total = res.total;
            this.list = res.data;
            
            // 如果之前播放的视频不在新列表中，确保播放状态已清除（实际上已经在上面清除了）
            // 这里保留逻辑以防万一，但通常不会执行到
            if (previousPlayingId && !this.list.find(item => item.id === previousPlayingId)) {
                this.playingId = null;
            }
        },
        change(value) {
            this.page = value;
            this.getList();
        },
        // 点击视频项时，播放当前视频并暂停其他视频
        router(item) {
            const currentVideo = this.getVideoElementById(item.id);
            if (!currentVideo) return;

            // 暂停所有其他正在播放的视频
            this.pauseAllVideosExcept(item.id);

            // 播放当前视频并记录ID
            this.playingId = item.id;
            if (currentVideo.paused) {
                currentVideo.play();
            }
        },

        // 根据视频ID获取对应的video元素
        getVideoElementById(videoId) {
            // 通过document.getElementById获取video元素，因为我们在模板中设置了id属性
            return document.getElementById('video_' + videoId);
        },

        // 暂停除指定ID外的所有视频
        pauseAllVideosExcept(exceptId) {
            // 遍历列表中的所有视频，暂停除指定ID外的所有正在播放的视频
            this.list.forEach(item => {
                if (item.id !== exceptId) {
                    const video = this.getVideoElementById(item.id);
                    if (video && !video.paused) {
                        video.pause();
                    }
                }
            });
        },

        // 当某个视频开始播放时，暂停其他视频，并记录当前视频ID
        onPlay(videoId) {
            // 暂停其他所有视频
            this.pauseAllVideosExcept(videoId);
            // 记录当前播放的视频ID
            this.playingId = videoId;
        },

        // 点击视频时切换播放/暂停，仅操作当前视频
        togglePlay(item) {
            const currentVideo = this.getVideoElementById(item.id);
            if (!currentVideo) return;
            
            if (currentVideo.paused) {
                // 先暂停其他视频，再播放当前视频，确保一次只播放一个
                this.pauseAllVideosExcept(item.id);
                this.playingId = item.id;
                currentVideo.play();
            } else {
                currentVideo.pause();
            }
        },

        // 暂停时，如果当前暂停的是正在播放的视频，则清除播放ID
        onPause(videoId) {
            if (this.playingId === videoId) {
                this.playingId = null;
            }
        },
        
        // 播放结束时，如果当前结束的是正在播放的视频，则清除播放ID
        onEnded(videoId) {
            if (this.playingId === videoId) {
                this.playingId = null;
            }
        },

        removeVideo(item, index) {
            this.$confirm(this.$t('live.删除该视频'), this.$t('msg.提示'), {
                confirmButtonText: this.$t('msg.确定'),
                cancelButtonText: this.$t('msg.取消'),
                type: 'warning'
            }).then(async () => {
                // 如果删除的是正在播放的视频，清除播放状态
                if (this.playingId === item.id) {
                    this.playingId = null;
                }
                
                let ids = [item.id].join(',');
                await this.$api.videoApi.deleteVideo({
                    video_id: ids
                })
                this.$message({
                    message: this.$t('msg.删除成功'),
                    type: 'success'
                });
                this.page = 1;
                this.getList();
            }).catch(() => { });
        },

        dialog_ok() {
            this.dialogVisible = false;

            if (this.list.length == this.limit) return;
            this.getList()
        }
    }
}
</script>
<style scoped lang="scss">
.video {
    min-width: 100%;
    min-height: 100%;
    border-radius: 10px 10px 0 0;
    padding: 24px;
    box-sizing: border-box;
    background: #FCFCFE;

    .title {
        font-weight: bold;
        font-size: 20px;
        color: #333333;
        padding-bottom: 16px;
        display: flex;
        justify-content: space-between;
    }

    .tabs {

        .item {
            width: 128px;
            height: 45px;
            line-height: 45px;
            text-align: center;

            color: #2273FF;
            font-weight: bold;
            font-size: 18px;
            margin-right: 36px;
            background: rgba(34, 115, 255, 0.5);

            background: #F0F3F6;

            border-radius: 8px 8px 8px 8px;


            cursor: pointer;

            &.active {
                color: #FFFFFF;

                background: #2273FF;
            }
        }
    }

    .list {
        height: calc(100vh - 50px - 18px - 24px - 160px);
        display: flex;
        flex-wrap: wrap;

        .item {
            width: 264px;
            height: 358px;
            border-radius: 12px;
            margin-top: 24px;
            margin-right: 24px;
            overflow: hidden;
            cursor: pointer;
            position: relative;

            .video_item {
                width: 100%;
                height: 100%;
                object-fit: fill;
                position: relative;
                z-index: 0;
            }

            .cover {
                width: 100%;
                height: 100%;
                position: absolute;
                left: 0;
                top: 0;
                z-index: 1;
            }

            .play {
                width: 36px;
                height: 36px;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                z-index: 2;
            }

            .dele {
                width: 40px;
                height: 40px;
                position: absolute;
                right: 14px;
                top: 14px;
                z-index: 2;
            }
        }
    }
}
</style>